package cn.com.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

/**
 * 同时实现多种Listener
 * 
 * @author Administrator
 *
 */
public class ListenerTest implements HttpSessionListener, ServletContextListener, ServletRequestListener {
	private Logger logger = Logger.getLogger(ListenerTest.class);

	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {
		// 销毁Request时被调用
		HttpServletRequest request = (HttpServletRequest) arg0.getServletRequest();
		long time = System.currentTimeMillis() - (Long) request.getAttribute("dateCreated");
		logger.info(request.getRemoteAddr() + "请求处理结束，用时" + time + "毫秒。");

	}

	@Override
	public void requestInitialized(ServletRequestEvent arg0) {
		// 创建Request时被调用
		HttpServletRequest request = (HttpServletRequest) arg0.getServletRequest();
		String uri = request.getRequestURI();// 访问的URL路径
		uri = request.getQueryString() == null ? uri : (uri + "?" + request.getQueryString());
		request.setAttribute("dateCreated", System.currentTimeMillis());
		logger.info("IP " + request.getRemoteAddr() + " 请求 " + uri);

	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// 销毁Servlet上下文时被调用
		ServletContext servletContext = arg0.getServletContext();// 即将被销毁的Servlet上下文
		logger.info("即将关闭：" + servletContext.getContextPath());

	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// 加载Servlet上下文时被调用
		ServletContext servletContext = arg0.getServletContext();// 新加载的Servlet上下文
		logger.info("即将启动：" + servletContext.getContextPath());

	}

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// 创建Session时被调用
		HttpSession session = arg0.getSession();// 新创建的Session
		logger.info("新创建一个session,ID为：" + session.getId());// 记录日志

	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// 销毁Session前被调用
		HttpSession session = arg0.getSession();
		logger.info("销毁一个session,ID为：" + session.getId());

	}

}
